package com.kouxin.appaccount.developer;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class DeveloperDao extends HibernateDaoSupport {

	public void insert(Developer developer) {
		this.getHibernateTemplate().save(developer);
	}
	
	public void loadSoftwares(Developer developer) {
		this.getHibernateTemplate().execute(new LoadSoftwares(developer));
	}
	
	private class LoadSoftwares implements HibernateCallback {
		private Developer developer;
		public LoadSoftwares(Developer developer) {
			this.developer = developer;
		}
		@Override
		public Object doInHibernate(Session session) throws HibernateException, SQLException {
			session.refresh(developer);
			Hibernate.initialize(developer.getSoftwares());
			return null;
		}
	}
	
	public Developer get(Serializable id) {
		return (Developer) this.getHibernateTemplate().get(Developer.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Developer> findByExample(Developer developer) {
		return (List<Developer>)this.getHibernateTemplate().findByExample(developer);
	}
	
	@SuppressWarnings("unchecked")
	public Developer login(Developer developer) {
		List list = this.getHibernateTemplate().findByExample(developer);
		if (list != null && list.iterator().hasNext()) {
			return (Developer)list.iterator().next();
		}
		return null;
	}
	
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		DeveloperDao dd = (DeveloperDao)ac.getBean("DeveloperDao");
		Developer transientInstance = new Developer();
		transientInstance.setUsername("appaccount4");
		transientInstance.setPassword("123456");
		transientInstance.setSN("1111113");
		dd.insert(transientInstance);
	}
}
